<?php
/**
 * Created by PhpStorm.
 * User: 13790
 * Date: 2018/3/16
 * Time: 16:04
 */
namespace app\common\model;
use app\common\validate\Admin as ValidadteAdmin;
use think\Model;

class Admin extends Base
{

    protected $autoWriteTimestamp = true ;


    public static function  init()
    {
        //回调函数  save 添加之前回调此函数
        self::event('before_insert', function ($admin) {
            $admin['status'] = 1;
            $pass = $admin['admin_pass'];
            //获取配置文件的设置参数
            $md5_pre = config('admin.md5_pre');
            //拼接进行md5加密
            $admin['admin_pass'] = md5($md5_pre . $pass);
        });
        //回调函数 添加成功之后回调此函数 after_insert
        self::event('after_insert',function($admin){
            $role_ids=$admin['role_ids'];
            foreach($role_ids as $k => $v){
                db('admin_role')->insert([
                    'admin_id'  =>  $admin['id'],
                    'role_id'   =>  $v
                ]);
            }
        });
    }


public function sel(){
        $where=[];
    $data=$this
        ->alias('a')
        ->field('a.*,group_concat(role_name) role_names')
        ->join('admin_role b','a.id=b.admin_id','LEFT')
        ->join('role c','b.role_id=c.id','LEFT')
        ->where($where)
        ->group('a.id')
        ->paginate(15);
    return $data;
}
public function addData(){
        $dt = input('post.');

        //判断是否有选择角色
        if(empty($dt['role_ids'])){
            return '请选择角色';
        }

        //先进行数据验证
        $validate = new ValidadteAdmin();
        //验证添加的场景
        if(!$validate->scene('add')->check($dt)){
            return $validate->getError();
        }

        //添加数据     allowField 为true 时， 会自动将不是数据库的字段过滤掉
        $res = $this->data($dt)->allowField(true)->save();
        if(!$res){
            return '添加失败';
        }
 }
 public function editData(){
     $data = input('post.');

     $validate = new ValidadteAdmin();

     if(!$validate->scene('edit')->check($data)){
         return $validate->getError();
     }

     if(empty($data['admin_pass']) && $data['admin_pass'] == ''){
         unset($data['admin_pass']);
         $res =$this->allowField(true)->save($data,['id'=>$data['id']]);
         if($res){
             return true;
         }
         return "编辑失败";
     }

     if(!$validate->scene('pass')->check($data)){
         return $validate->getError();
     }

     $data['admin_pass'] = md5(config('admin.md5_pre').$data['admin_pass']);
     $res =$this->allowField(true)->save($data,['id'=>$data['id']]);
     if($res){
         return true;
     }
     return "编辑失败";
 }

}